package com.aiyige.page.globalsearch;

import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.api.apiengine.ModuleEngine;
import com.aiyige.base.api.apiengine.OrderEngine;
import com.aiyige.model.Keyword;
import com.aiyige.model.Page;
import com.aiyige.model.moment.entity.MajorCourse;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.model.moment.entity.TrainingCard;
import com.aiyige.model.moment.entity.TrainingCourse;
import com.aiyige.page.detail.DetailPage;
import com.aiyige.page.globalsearch.adapter.DynamicAdapter;
import com.aiyige.page.globalsearch.adapter.KeywordAssociateAdapter;
import com.aiyige.page.globalsearch.adapter.LearnVideoAdapter;
import com.aiyige.page.globalsearch.adapter.MajorCourseAdapter;
import com.aiyige.page.globalsearch.adapter.TraingCardAdapter;
import com.aiyige.page.globalsearch.adapter.TraingClassAdapter;
import com.aiyige.page.globalsearch.model.KeywordAssociateItem;
import com.aiyige.page.globalsearch.model.SearchGroup;
import com.aiyige.page.globalsearch.util.SearchUtil;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.HighLightWordUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.KeyboardUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.CommonDataView;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;

@Route(path = ARouterConfig.GlobalDetailSearchPage)
public class GlobalDetailSearchPage extends AppCompatActivity implements CommonDataView.RetrofitStub {
    public static final String TAG = GlobalDetailSearchPage.class.getSimpleName();
    public static final int HANDLE_SEARCH = 1;
    @BindView(R.id.inputEt)
    EditText inputEt;
    @BindView(R.id.cdv)
    CommonDataView cdv;
    @BindView(R.id.keywordAssociateRv)
    RecyclerView keywordAssociateRv;
    @BindView(R.id.keywordAssociateLayout)
    FrameLayout keywordAssociateLayout;
    @Autowired
    int type;
    @Autowired
    String searchWord;
    BaseQuickAdapter baseQuickAdapter;

    Handler mainHandler;
    Handler searchHandler;
    HandlerThread searchThread;
    TextWatcher searchTextWatcher;
    KeywordAssociateAdapter keywordAssociateAdapter;
    @BindView(R.id.inputEtClearBtn)
    ImageView inputEtClearBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_global_detail_search);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        inputEt.setText(searchWord);
        keywordAssociateRv.setLayoutManager(new LinearLayoutManager(this));
        keywordAssociateAdapter = new KeywordAssociateAdapter();
        keywordAssociateAdapter.bindToRecyclerView(keywordAssociateRv);
        keywordAssociateAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                searchWord = keywordAssociateAdapter.getItem(position).getKeyword();
                inputEt.removeTextChangedListener(searchTextWatcher);
                inputEt.setText(searchWord);
                inputEt.addTextChangedListener(searchTextWatcher);
                hideKeywordAssociate();
                cdv.refresh();
            }
        });
        searchTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    inputEtClearBtn.setVisibility(View.INVISIBLE);
                    hideKeywordAssociate();
                    keywordAssociateAdapter.setNewData(null);
                } else {
                    inputEtClearBtn.setVisibility(View.VISIBLE);
                    showKeywordAssociate();
                    doSearch(s.toString());
                }
            }
        };
        inputEt.addTextChangedListener(searchTextWatcher);
        inputEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(v.getText().toString())) {
                        searchWord = v.getText().toString();
                        hideKeywordAssociate();
                        KeyboardUtil.hideKeyboard(v.getContext(), v);
                        cdv.refresh();
                        return true;
                    }
                }
                return false;
            }
        });

        mainHandler = new Handler(Looper.getMainLooper());
        searchThread = new HandlerThread(TAG + "SearchThread");
        searchThread.start();
        searchHandler = new Handler(searchThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HANDLE_SEARCH:
                        String searchStr = (String) msg.obj;
                        final List<KeywordAssociateItem> resultList = new LinkedList<>();
                        if (!TextUtils.isEmpty(searchStr)) {
                            try {
                                Response<ResponseBody> response = ApiManager.getService().searchKeywordAssociate(searchStr).execute();
                                if (response.code() != ResponseCode.OK) {
                                    throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                                }
                                String json = RetrofitUtil.getResponseBodyAsString(response);
                                List<Keyword> keywordList = JSON.parseArray(json, Keyword.class);
                                for (Keyword keyword : keywordList) {
                                    resultList.add(KeywordAssociateItem.newBuilder()
                                            .keyword(keyword.getKeyword())
                                            .build());
                                }
                            } catch (Exception e) {

                            }
                        }
                        mainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                keywordAssociateAdapter.setNewData(resultList);
                            }
                        });
                        break;
                }
            }
        };


        switch (type) {
            case SearchUtil.TYPE_DYNAMIC:
                baseQuickAdapter = new DynamicAdapter();
                baseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        SearchGroup.Sample sample = (SearchGroup.Sample) adapter.getItem(position);
                        switch (sample.getType()) {
                            case SearchUtil.TYPE_INFO:
                                Router.start(sample.getRouter());
                                break;
                            case SearchUtil.TYPE_VIDEO:
                                Router.start(sample.getRouter());
                                break;
                            case SearchUtil.TYPE_PHOTO:
                                Router.start(sample.getRouter());
                                break;
                        }
                    }
                });
                break;
            case SearchUtil.TYPE_LEARN_VIDEO:
                baseQuickAdapter = new LearnVideoAdapter();
                baseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        SearchGroup.Sample sample = (SearchGroup.Sample) adapter.getItem(position);
                        Router.start(sample.getRouter());
                    }
                });
                break;
            case SearchUtil.TYPE_MAJOR_COURSE:
                baseQuickAdapter = new MajorCourseAdapter();
                baseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        SearchGroup.Sample sample = (SearchGroup.Sample) adapter.getItem(position);
                        Router.start(sample.getRouter());
                    }
                });
                break;
            case SearchUtil.TYPE_TRAING_CLASS:
                baseQuickAdapter = new TraingClassAdapter();
                baseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        SearchGroup.Sample sample = (SearchGroup.Sample) adapter.getItem(position);
                        Router.start(sample.getRouter());
                    }
                });
                break;
            case SearchUtil.TYPE_TRAING_CARD:
                baseQuickAdapter = new TraingCardAdapter();
                baseQuickAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        SearchGroup.Sample sample = (SearchGroup.Sample) adapter.getItem(position);
                        Router.start(sample.getRouter());
                    }
                });
                break;
            default:
                ToastX.show(R.string.unknown_error);
                finish();
                return;
        }
        inputEt.setFilters(new InputFilter[]{new InputNumFilter(30, false)});
        cdv.config(baseQuickAdapter, this);
        cdv.doRefreshRequest();
    }

    private void doSearch(String searchStr) {
        Message msg = Message.obtain();
        msg.what = HANDLE_SEARCH;
        msg.obj = searchStr;
        searchHandler.removeMessages(HANDLE_SEARCH);
        searchHandler.sendMessage(msg);
    }

    @OnClick({R.id.cancelBtn, R.id.inputEtClearBtn})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.cancelBtn:
                finish();
                break;
            case R.id.inputEtClearBtn:
                inputEt.setText("");
                break;
        }
    }

    @Override
    public Call<ResponseBody> call(long currentPage) {
        List<String> subjectList;
        switch (type) {
            case SearchUtil.TYPE_DYNAMIC:
                subjectList = Arrays.asList(Moment.SUBJECT_VIDEO, Moment.SUBJECT_ARTICLE, Moment.SUBJECT_PHOTO);
                break;
            case SearchUtil.TYPE_LEARN_VIDEO:
                subjectList = Arrays.asList(Moment.SUBJECT_VIDEO_COURSE);
                break;
            case SearchUtil.TYPE_MAJOR_COURSE:
                subjectList = Arrays.asList(Moment.SUBJECT_MAJOR_COURSE);
                break;
            case SearchUtil.TYPE_TRAING_CLASS:
                subjectList = Arrays.asList(Moment.SUBJECT_TRAINING_COURSE);
                break;
            case SearchUtil.TYPE_TRAING_CARD:
                subjectList = Arrays.asList(Moment.SUBJECT_TRAINING_CARD);
                break;
            default:
                subjectList = new LinkedList<>();
                break;
        }
        return ApiManager.getService()
                .searchMoment(ModuleEngine.SEARCH_ZONE, OrderEngine.LATEST, subjectList, searchWord, 15, currentPage);
    }

    @Override
    public CommonDataView.HandleResult handleResponse(String respJson, List resultList) {
        try {
            Page page = JSON.parseObject(respJson, Page.class);
            List<Moment> momentList = new LinkedList<>();
            if (!TextUtils.isEmpty(page.getContent())) {
                momentList.addAll(JSON.parseArray(page.getContent().toString(), Moment.class));
            }
            for (Moment item : momentList) {
                Moment moment = new Moment(item);
                SearchGroup.Sample sample = new SearchGroup.Sample();
                sample.setViewCount(moment.getStatisticsBackup().getViewCount());
                sample.setId(moment.getId());
                sample.setCover(ListUtil.isEmpty(moment.getCover()) ? "" : moment.getCover().get(0));
                sample.setTitle(HighLightWordUtil.highLight(moment.getTitle(), searchWord));
                sample.setOwner(moment.getCreatorBackup().getName());
                sample.setOwnerId(moment.getCreator());
                sample.setOwnerLevel(moment.getCreatorBackup().getLevel());
                sample.setOwnerAvatar(moment.getCreatorBackup().getAvatar());
                sample.setCategoryId(moment.getCategoryId());
                sample.setCity(moment.getCityId());
                sample.setRouter(moment.getRouter());
                switch (moment.getSubject()) {
                    case Moment.SUBJECT_ARTICLE:
                        sample.setType(SearchUtil.TYPE_INFO);
                        break;
                    case Moment.SUBJECT_VIDEO_COURSE:
                        sample.setType(SearchUtil.TYPE_LEARN_VIDEO);
                        sample.setStages(moment.getMediaSummary().getCount());
                        sample.setOriginPrice(moment.getCommodityBackup().getOriginPrice());
                        sample.setPrice(moment.getCommodityBackup().getPrice());
                        sample.setDurationTotal(moment.getMediaSummary().getDuration());
                        sample.setSellCount(moment.getStatisticsBackup().getSellCount());
                        break;
                    case Moment.SUBJECT_PHOTO:
                        sample.setType(SearchUtil.TYPE_PHOTO);
                        sample.setStages(moment.getMediaSummary().getCount());
                        break;
                    case Moment.SUBJECT_VIDEO:
                        sample.setType(SearchUtil.TYPE_VIDEO);
                        sample.setStages(moment.getMediaSummary().getCount());
                        sample.setDurationTotal(moment.getMediaSummary().getDuration());
                        break;
                    case Moment.SUBJECT_MAJOR_COURSE:
                        sample.setType(SearchUtil.TYPE_MAJOR_COURSE);
                        try {
                            MajorCourse majorCourse = JSON.parseObject(moment.getMoreBackup(), MajorCourse.class);
                            sample.setDurationTotal(majorCourse.getClassCount());
                        } catch (Exception e) {
                            sample.setDurationTotal(0);
                        }
                        break;
                    case Moment.SUBJECT_TRAINING_COURSE:
                        sample.setType(SearchUtil.TYPE_TRAING_CLASS);
                        try {
                            TrainingCourse trainingCourse = JSON.parseObject(moment.getMoreBackup(), TrainingCourse.class);
                            sample.setDurationTotal(trainingCourse.getClassCount());
                        } catch (Exception e) {
                            sample.setDurationTotal(0);
                        }
                        break;
                    case Moment.SUBJECT_TRAINING_CARD:
                        try {
                            TrainingCard trainingCard = JSON.parseObject(moment.getMoreBackup(), TrainingCard.class);
                            switch (trainingCard.getCardType()) {
                                case Moment.TRAINING_CARD_TYPE_TIME_CARD:
                                    sample.setType(SearchUtil.TYPE_TRAING_CARD_TIME_CARD);
                                    break;
                                case Moment.TRAINING_CARD_TYPE_MEASURED_CARD:
                                    sample.setType(SearchUtil.TYPE_TRAING_CARD_COUNT_CARD);
                                    break;
                                case Moment.TRAINING_CARD_TYPE_RECHARGEABLE_CARD:
                                    sample.setType(SearchUtil.TYPE_TRAING_CARD_PREPAID_CARD);
                                    break;
                            }
                        } catch (Exception e) {
                            sample.setType(SearchUtil.TYPE_TRAING_CARD_COUNT_CARD);
                        }
                        break;
                }
                resultList.add(sample);
            }
            return new CommonDataView.HandleResult(page.isLast());
        } catch (Exception e) {
            return new CommonDataView.HandleResult(e.getMessage());
        }

    }

    public void showKeywordAssociate() {
        keywordAssociateLayout.setVisibility(View.VISIBLE);
    }

    public void hideKeywordAssociate() {
        keywordAssociateLayout.setVisibility(View.INVISIBLE);
    }
}
